package Affair;

import com.mysql.cj.jdbc.ConnectionWrapper;
import util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Jason
 * @PACKAGE_NAME Affair
 * @Description 事务
 * @date 2023-12-06 16:17
 */
public class Test {
    /**
     * 转出操作
     * @param conn
     * @param name
     * @param money
     * @throws SQLException
     */
    public static void outMoney(Connection conn,String name,int money) throws SQLException {
        String sql = "update cont set money = money - ? where name = ?";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setInt(1,money);
        pst.setString(2,name);
        pst.executeUpdate();
        int a = 1/0;//错误状态
    }

    /**
     * 转入操作
     * @param conn
     * @param name
     * @param money
     * @throws SQLException
     */
    public static void inMoney(Connection conn,String name,int money) throws SQLException {
        String sql = "update cont set money = money + ? where name = ?";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setInt(1,money);
        pst.setString(2,name);
        pst.executeUpdate();
    }

    public static void main(String[] args) throws SQLException {
        DbUtil dbUtil = new DbUtil();
        Connection conn = null;
        try {
            conn = dbUtil.getConnection();
            conn.setAutoCommit(false);//取消自动提交
            System.out.println("A给B");
            int money = 100;
            outMoney(conn,"A",money);
            inMoney(conn,"B",money);
            System.out.println("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            conn.rollback();//回滚操作
        } finally {
            conn.commit();//提交事务
            conn.close();
        }
    }
}
